# coding:utf-8
"""
Author: r.xw
Date: 2024/1/6
File: email_utils.py
"""
import logging
import random
import smtplib
import string
from email.header import Header
from email.mime.text import MIMEText

from app.config.config import config
from app.settings import env


def gen_email_code():
    lst = random.sample(string.ascii_letters + string.digits, 6)
    return ''.join(lst)


def send_email(email, message, subject):
    mail_host = config[env].email_host
    mail_user = config[env].email_name
    mail_password = config[env].email_password

    sender = config[env].email_name
    receivers = email

    message = MIMEText(message, 'html', 'utf-8')

    message['From'] = Header(sender)
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtp = smtplib.SMTP()
        smtp.connect(mail_host, 25)
        smtp.login(mail_user, mail_password)
        smtp.sendmail(sender, receivers, message.as_string())
        logging.info('邮件发送成功')
    except smtplib.SMTPException as e:
        logging.error("%s" % e)
        raise e
